package com.bwei.like.mostitemnews.fragment;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;

import com.bwei.like.mostitemnews.R;
import com.bwei.like.mostitemnews.adapater.MyAdapater;
import com.bwei.like.mostitemnews.bean.Bean;
import com.bwei.like.mostitemnews.utils.ImageLoaderUtils;
import com.bwei.like.mostitemnews.utils.MD5Encoder;
import com.google.gson.Gson;
import com.nostra13.universalimageloader.core.ImageLoader;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.Executors;

/**
 * Created by LiKe on 2016/11/22.
 */
public class MilitaryFragment extends Fragment {

    private ListView listView;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_item, null);
        listView = (ListView) view.findViewById(R.id.fragment_listView);
        return view;
    }


    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        //获取数据
        getData("http://r.inews.qq.com/getQQNewsIndexAndItems?uid=619431845e12918c&Cookie=%20lskey%3D00030000accb0234fdc6e7cb2d51f928d128d11bf7a936ba8dda3001c8e57b2c059504015bcaf96c9bd1ae8f%3B%20luin%3Do0731917814%3B%20skey%3DMFIkNzO9NN%3B%20uin%3Do0731917814%3B%20logintype%3D0%20&qn-rid=1334658299&store=274&hw=bignox_NoxW&devid=352284040000006&qn-sig=1ec9072eabb673a628b8a0e33ff46d76&screen_width=900&mac=0A%253A00%253A27%253A00%253A00%253A00&chlid=news_news_mil&appver=19_android_4.8.0&qqnetwork=wifi&mid=d7568868be0e7c4c4850af6c0f6e93cc1b7a5743&imsi=310260000000000&apptype=android&screen_height=1399");
    }


    private void getData(String path) {

        String data = getDataFromLocal(path);
        if (!TextUtils.isEmpty(data)) {
            //如果本地数据不为空的话，获取本地数据进行解析
            Log.i("TAG", "getData: " + data);
            getJsonData(data);
        } else {
            //请求网络
            getDataFromNet(path);
        }
    }

    private void getJsonData(String data) {
        Gson gson = new Gson();
        final Bean bean =gson.fromJson(data, Bean.class);
        listView.setAdapter(new MyAdapater(bean, getActivity()));
//        for (int i = 0; i < bean.getIdlist().get(0).getNewslist().size(); i++) {
//            final List<String> thumbnails_qqnews = bean.getIdlist().get(0).getNewslist().get(i).getThumbnails_qqnews();
//            if (thumbnails_qqnews.size() == 1){
//                Executors.newFixedThreadPool(5).execute(new Runnable() {
//                    @Override
//                    public void run() {
//                        ImageLoader.getInstance().loadImageSync(thumbnails_qqnews.get(0), ImageLoaderUtils.initOptions());
//                    }
//                });
//            }else {
//                Executors.newFixedThreadPool(5).execute(new Runnable() {
//                    @Override
//                    public void run() {
//                        ImageLoader.getInstance().loadImageSync(thumbnails_qqnews.get(0),ImageLoaderUtils.initOptions());
//                    }
//                });
//
//                Executors.newFixedThreadPool(5).execute(new Runnable() {
//                    @Override
//                    public void run() {
//                        ImageLoader.getInstance().loadImageSync(thumbnails_qqnews.get(1),ImageLoaderUtils.initOptions());
//                    }
//                });
//
//                Executors.newFixedThreadPool(5).execute(new Runnable() {
//                    @Override
//                    public void run() {
//                        ImageLoader.getInstance().loadImageSync(thumbnails_qqnews.get(2),ImageLoaderUtils.initOptions());
//                    }
//                });
//            }
//        }
    }

    private void getDataFromNet(final String path) {
        Log.i("TAG", "getDataFromNet: " + path);
        RequestParams requestParams = new RequestParams(path);
        x.http().get(requestParams, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String s) {
                Log.i("TAG***********", "onSuccess: " + s);
                //如果解析成功就将数据写入到本地中
                writeDataToLocal(s, path);
                getJsonData(s);

            }

            @Override
            public void onError(Throwable throwable, boolean b) {

            }

            @Override
            public void onCancelled(CancelledException e) {

            }

            @Override
            public void onFinished() {
                Log.i("ssssss", "onFinished: ");
            }
        });
    }

    private void writeDataToLocal(String s, String path) {
        //获取路径
        File cacheDir = getActivity().getCacheDir();
        File file = null;
        try {
            file = new File(cacheDir, MD5Encoder.encode(path));
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (!file.exists()) {
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        //创建流
        BufferedWriter bufferedWriter = null;
        try {
            bufferedWriter = new BufferedWriter(new FileWriter(file.getAbsolutePath()));
            bufferedWriter.write(s);
            bufferedWriter.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (bufferedWriter != null)
                    bufferedWriter.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    //获取本地数据
    private String getDataFromLocal(String path) {
        File cacheDir = getActivity().getCacheDir();
        File file = null;
        try {
            file = new File(cacheDir, MD5Encoder.encode(path));
        } catch (Exception e) {
            e.printStackTrace();
        }
        BufferedReader bufferedReader = null;
        try {
            bufferedReader = new BufferedReader(new FileReader(file.getAbsolutePath()));
            String line = null;
            StringBuilder stringBuilder = new StringBuilder();
            while ((line = bufferedReader.readLine()) != null) {
                stringBuilder.append(line);
            }

            return stringBuilder.toString();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (bufferedReader != null)
                    bufferedReader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }


}
